<?php
/*
 * Copyright (c) Taras Kudla, 2010
 */
define("_MAX_FILE_SIZE",1048576);
define("_MAX_DB_RECORDS",1000);
define("_AUTH_LOG","auth.log");
define("_SYS_LOG","sys.log");
define("_ERROR_LOG","error.log");

class log extends kernel
	{
	
	private $logTable="log";
	private $logFile=_SYS_LOG;
	private $MAXPERLIFE=100;
	private $CALLEDFILE=0;
	
	public function init(){
		
	}
	# getting logs level
	public function GetLevel($level){
		switch($level){		
			case _LOG_MESSAGE: return "MESSAGE";break;	
			case _LOG_NOTICE: return "NOTICE ";break;
	    	case _LOG_ERROR: return "ERROR  ";break;
			case _LOG_CRITICAL: return "CRITICAL";break;
			default: return "UNKNOWN";
		}
	}
	
	public function write($message,$level=_LOG_MESSAGE,$file=_SYS_LOG,$name=null)
		{
		if($name==null){
				//$name=($this->core->ENV_LAYER==_ENV_KERNEL?"KERNEL":strtolower($this->core->ENV_CALLER["MOD"])."-".strtolower($this->core->ENV_CALLER["NAME"]));
		}
		$remoteAddr = isset($_SERVER["REMOTE_ADDR"])?$_SERVER["REMOTE_ADDR"]:"unknown";
		list($name,$level,$ip)=$this->core->escapeList($name,$level,$remoteAddr);
		$date=date("Y-m-d H:i:s");
		if($this->core->get("logtofile")==YES){
			$this->WriteToFile($name,$message,$file,$level);				
		}
		return true;
		}
		
	public function WriteToFile($from,$message,$filetype=_SYS_LOG,$level=_LOG_MESSAGE){
		$this->CheckForArchiving($filetype);	
		$remoteAddr = isset($_SERVER["REMOTE_ADDR"])?$this->core->escapeString($_SERVER["REMOTE_ADDR"]):"unknown";
		$line=date("M j H:i:s ").$remoteAddr." ".$this->GetLevel($level)." ".(  $this->core->isloaded("user")?$this->core->user->GetUserFingerprint():null)." ".$from.": ".$message."\r\n";
		$logsfile = $this->core->parseasdir($this->core->get("logsdir"));
		$file=$logsfile.$filetype;
		if( !is_writable($file) ){
			$this->core->error("LOG"," Cannot create/open log file ($file). Please create it and|or change permissions.",null,false);			
		} else {
			$f=fopen($file,"a+");
			fwrite($f,$line);
			fclose($f);
		}
	}
			
	private function CheckForArchiving($filetype=_SYS_LOG){
		
		$dir = $this->core->parseasdir($this->core->get("logsdir"));
		$file = $dir.$filetype;
		if(file_exists($file) && filesize($file) > _MAX_FILE_SIZE){
			if(!is_writable($dir)){
				$this->core->error("LOG","Directory is not writable. Cannot write to log archives",null,false);
				return false;			
			}
			if(extension_loaded("zlib")){
			$in = fopen($file,"r");
			$out= fopen($file.".".date("U").".gz","w+");
			while(!feof($in)){
				$buffer = fread($in,4096);
				fwrite($out,gzencode($buffer,9));	
			}				
			fclose($in);
			fclose($out);
			$clean=fopen($file,"w+");
			fwrite($clean,null);
			fclose($clean);
			} else {
			
			copy($file,$file.".".date("U")."log");
			
			}			
		
			return true;
		}
		
		return false;
	}
	
	public function checkaccess(){
	
	}
	
	public function export(){
	
	
	}
		
	public function void(){


	}	
	
	
}?>
